package m.jclecai.com.activity;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.adapter.ChampionAdapter;
import m.jclecai.com.adapter.holder.ChampionHolder;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.ChampionBean;
import m.jclecai.com.bean.RecordsBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.pop.MyLotteryMenuPopUpWindow;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;

/**
 * Created by zed on 2018/4/8.
 */

public class ChampionActivity extends BaseActivity {

    @BindView(R.id.ptr_listView)
    PullToRefreshListView ptr_listView;
    @BindView(R.id.toolbar_hiti)
    TextView toolbarHiti;
    ChampionAdapter adapter;
    MyLotteryMenuPopUpWindow popUpWindow;
    private int pager = 0;
    List<RecordsBean> beans;
    List<RecordsBean> selectBall;
    String[] names = new String[]{"世界杯冠军", "世界杯冠亚军"};
    String[] types = new String[]{"0", "1"};

    @Override
    protected int getContentView() {
        return R.layout.activity_champion;
    }

    @Override
    protected void initView() {
        super.initView();
        showLoadingLayout(ptr_listView);
        showExceptButton(false);
        leftOptionText("");
        setTitle("世界杯冠军", R.drawable.gs);
    }

    @Override
    protected void initData() {
        super.initData();
        selectBall = new ArrayList<>();
        beans = new ArrayList<>();
        adapter = new ChampionAdapter(beans, this);
        ptr_listView.setAdapter(adapter);
        ptr_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RecordsBean bean = beans.get(position - 1);
                if (!bean.getIsclose().equals("1")){
                    bean.setChecked(!bean.isChecked());
                    ((ChampionHolder) view).setCheck(bean.isChecked());
                    if (bean.isChecked()) selectBall.add(bean);
                    else selectBall.remove(bean);
                    toolbarHiti.setText("已选" + selectBall.size() + "支球队");
                }
            }
        });
        ptr_listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                getList();
            }
        });
        getList();
        iniPopupWindow();
    }

    void getList() {
        String param = "";
        if (pager == 1)
            param = "?type=1";
        HttpManager.getAsyn(Constant_Url.CUP_INDEX + param, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                showInternetOffLayout();
                if (ptr_listView != null) ptr_listView.onRefreshComplete();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (beans != null)
                    beans.clear();
                if (ptr_listView != null) ptr_listView.onRefreshComplete();
                closeLoadingLayout();
                ChampionBean championBean = FastOk.get(response, ChampionBean.class);
                if (championBean != null){
                    List<RecordsBean> records = championBean.getRecords();
                    if (null!=records&&records.size()>0&&!records.equals("[]")){
                        beans.addAll(championBean.getRecords());
                    }

                }
                if (adapter != null)
                    adapter.notifyDataSetChanged();
                if (beans != null && beans.size() <= 0)
                    showEmptyLayout("暂无比赛~", R.mipmap.img_blank_match);
                if (selectBall != null) selectBall.clear();
                if (toolbarHiti != null) toolbarHiti.setText("已选" + selectBall.size() + "支球队");
            }
        });
    }

    private void iniPopupWindow() {
        popUpWindow = new MyLotteryMenuPopUpWindow(this, names, types, pager, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                setTitle(names[position]);
                pager = position;
                popUpWindow.notifyDataSetChanged();
                if (popUpWindow.isShowing()) {
                    popUpWindow.dismiss();
                }
                showDialog();
                getList();

            }
        }, new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                startAnimation(ivTitleIcon, R.anim.rotate_180_360);
            }
        });
    }

    @OnClick({R.id.tv_back, R.id.toolbar_delete, R.id.toolbar_confirm,
            R.id.tv_mid_title, R.id.tv_right_option, R.id.iv_title_icon})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                onBackPressed();
                break;
            case R.id.toolbar_delete:
                clearData();
                break;
            case R.id.toolbar_confirm:
                Intent intent = new Intent(this, BettingChampionActivity.class);
                intent.putExtra("name", names[pager]);
                intent.putExtra("pager", pager);
                intent.putExtra("data", FastOk.string(selectBall));
                //跳转到投注界面
                startActivityForResult(intent, Constant_Result.SYNCHRONIZATION);
                break;
            case R.id.iv_title_icon:
            case R.id.tv_mid_title:
                startAnimation(ivTitleIcon, R.anim.rotate_0_180);
                popUpWindow.setPager(pager);
                popUpWindow.showAsDropDown(rlBar);
                break;
            case R.id.tv_right_option:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == Constant_Result.SYNCHRONIZATION && resultCode == RESULT_OK) {
            //同步数据
            if (intent != null && intent.hasExtra("data")) {
                String data = intent.getStringExtra("data");
                List<RecordsBean> list = FastOk.getList(data, RecordsBean.class);

                Iterator<RecordsBean> iterator = selectBall.iterator();
                while (iterator.hasNext()) {
                    RecordsBean next = iterator.next();
                    boolean notExist = true;
                    for (RecordsBean b : list) {//判断投注页面返回的数据是否与数据源匹配
                        if (next.getId().equals(b.getId())) {
                            notExist = false;
                            break;
                        }
                    }
                    if (notExist) {//如果返回的数据没有与之匹配的移除掉
                        next.setChecked(false);
                        iterator.remove();
                    }
                }
                if (toolbarHiti != null) toolbarHiti.setText("已选" + selectBall.size() + "支球队");
                if (adapter != null) adapter.notifyDataSetChanged();
            }
        }
    }

    void clearData() {
        if (selectBall == null) return;
        Iterator<RecordsBean> iterator = selectBall.iterator();
        while (iterator.hasNext()) {
            RecordsBean next = iterator.next();
            next.setChecked(false);
            iterator.remove();
        }
        if (toolbarHiti != null) toolbarHiti.setText("已选" + selectBall.size() + "支球队");
        if (adapter != null) adapter.notifyDataSetChanged();
    }
}
